'''
Created on Nov 29, 2010

@author: dexen
'''

import dexen
from dexen import Score, Individual

import random

ALIVE = "Alive"
DEAD = "Dead"

GEN_SIZE = 2
MUTATION_PROB  = 1/GEN_SIZE * 3

#INITIALISATION 
#function for generating genotype
def random_genotype(size):
    genotype = []
    for _ in range(size):
        random.seed()
        genotype.append(random.random())
    return genotype

class MyInd(Individual):
    def __init__(self):
        Individual.__init__(self)
        self.genotype = random_genotype(GEN_SIZE)
        self.phenotype = None
        self.perimeter = Score("perimeter", None, "Perimeter", dexen.MINIMIZE)
        self.area = Score("area", None, "Area", dexen.MAXIMIZE)
        self.state = ALIVE

    def reproduce(self, ind):
        child1 = MyInd()
        child2 = MyInd()
        child1.genotype = []
        child2.genotype = []
       
        z = random.randint(1, GEN_SIZE-2)
       
        for i in range(z):
            child1.genotype.append(self.genotype[i])
            child2.genotype.append(ind.genotype[i])
           

        for i in range(z, GEN_SIZE):
            child1.genotype.append(ind.genotype[i])
            child2.genotype.append(self.genotype[i])

        random.seed()
        for g_num in range(GEN_SIZE):
            if random.random() < MUTATION_PROB:
                child1.genotype[g_num] = random.random()
            if random.random() < MUTATION_PROB:
                child2.genotype[g_num] = random.random()

        return child1, child2
    
    def kill(self):
        self.state = DEAD
    
    def is_alive(self):
        return self.state == ALIVE 
    
    def __repr__(self):
        out = "---------- Individual ----------\n"
        out += "Id: {0}\n".format(self._get_id()) 
        out += "Genotype: {0}\n".format(self.genotype)
        out += "Phenotype: {0}\n".format(self.phenotype)
        out += "Perimeter: {0}\n".format(self.perimeter.value)
        out += "Area: {0}\n".format(self.area.value)
        out += "-------------------------------\n"
        return out


#===============================================================================
# Testing
#===============================================================================
def test():
    ind = MyInd()
    print ind
    
if __name__ == "__main__":
    test()
    